package com.fqy.thread02.compare;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * User: fqy
 * Date: 2021/9/1
 * Time: 21:26
 * Describe:
 * 1 synchronized是java的内置关键字而ReentrantLock时java5以后的新发布的类
 * 2 synchronized一旦申请，如果获取不到锁会一直阻塞，这个阻塞的过程，用户无法控制
 */
public class Resource {

    public synchronized void resource01(){

        System.out.println(Thread.currentThread().getName()+"\t"+"---come in");
        //暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Lock lock = new ReentrantLock();
    public void resource02() throws InterruptedException {
//        lock.lock();
        if (lock.tryLock(1,TimeUnit.SECONDS)) {
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "---come in");
                try {
//                    TimeUnit.SECONDS.sleep(3);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "\t" + "---抢锁失败");
        }
    }
}
